//
//  DBbase.m
//  edu
//
//  Created by baobaodp on 13-9-28.
//  Copyright (c) 2013年 baobaodp. All rights reserved.
//

#import "DBbase.h"
#import "Record.h"

@implementation DBbase

DBbase *dBbase;
@synthesize database;

-(id)initWithDBName:(NSString *) name
{
    if(self=[super init])
    {
        
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSLog(@"documentsDirectory: %@",documentsDirectory);
        
        
        
        NSString *databaseFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db",name] ];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];

        if(![fileManager fileExistsAtPath:databaseFilePath]) //如果不存在
        {
            NSLog(@"db is not exist");
            NSString *dataPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/edu.db"];//获取程序包中相应文件的路径
            NSError *error;
            if([fileManager copyItemAtPath:dataPath toPath:databaseFilePath error:&error]) //拷贝
            {
                NSLog(@"copy db success");
            }
            else 
            {
                NSLog(@"%@",error);
            }  
        }
        
        if (sqlite3_open([databaseFilePath UTF8String], &database)==SQLITE_OK) {
            NSLog(@"open sqlite db:%@ ok.",name);
        }else{
            NSLog(@"open sqlite db fail.");
        }

    }
    return self;
}

id getColumnString(sqlite3_stmt *statement, int colIdx)
{
    int type = sqlite3_column_type(statement, colIdx);
    
    if(type == SQLITE_INTEGER){
        int d = sqlite3_column_int(statement, colIdx);
        return  [NSString stringWithFormat:@"%d",d];
    }else if(type == SQLITE_FLOAT){
        float d = sqlite3_column_double(statement, colIdx);
        return  [NSString stringWithFormat:@"%f",d];
    }else if(type == SQLITE_BLOB){
        NSData* data = nil;
        
        int length = sqlite3_column_bytes(statement, colIdx);
        data       = [NSData dataWithBytes:sqlite3_column_blob(statement, colIdx) length:length];

        return data;
    }else if(type == SQLITE_NULL){
        return @"";
    }else{
        char *d = (char *)sqlite3_column_text(statement, colIdx);
        if(d == NULL){
            return @"";
        }
        NSString *v=[[NSString alloc] initWithCString:(char *)d encoding:NSUTF8StringEncoding];
        return v;
    }
    return @"";
}

NSMutableArray* getDbList(const char* sql)
{
    sqlite3_stmt *statement;
    
    NSMutableArray *list = [[NSMutableArray alloc]init];
    
    if (sqlite3_prepare_v2(dBbase.database, sql, -1, &statement, nil)!=SQLITE_OK) {
        NSLog(@"select fail:%s",sql);
        //[estimationViewController showMsg:@"select db fail."];
        return list;
    }
    
    while(sqlite3_step(statement) == SQLITE_ROW){
        NSMutableArray *a = [[NSMutableArray alloc]init];
        int cols = sqlite3_column_count(statement);
        for(int i=0; i<cols; i++){
            [a addObject:getColumnString(statement, i)];
        }
        [list addObject:a];
    }
    
    sqlite3_finalize(statement);
    
    return list;
}

NSData* LoadImagesFromSql(const char* imageLink)
{
    NSData* data = nil;
   
    sqlite3_stmt* statement;
    
    if( sqlite3_prepare_v2(dBbase.database, imageLink, -1, &statement, NULL) == SQLITE_OK )
    {
        if( sqlite3_step(statement) == SQLITE_ROW )
        {
            int length = sqlite3_column_bytes(statement, 0);
            data       = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
        }
    }
    
    // Finalize and close database.
    sqlite3_finalize(statement);
    
    return data;
    
}

NSMutableArray* getDbRecords(const char* sql , NSString* tableName , NSArray* keyNames)
{
    sqlite3_stmt *statement;
    
    //NSMutableArray *list = [[[NSMutableArray alloc]init]autorelease];
    NSMutableArray *list = [[NSMutableArray alloc]init];
    
    if (sqlite3_prepare_v2(dBbase.database, sql, -1, &statement, nil)!=SQLITE_OK) {
        NSLog(@"select fail:%s",sql);
        //NSLog(@"fail code:%s",sqlite3_errmsg(statement));
        
        //[estimationViewController showMsg:@"select db fail."];
        return list;
    }
    NSLog(@"sql:%s",sql);
    while(sqlite3_step(statement) == SQLITE_ROW){
        Record *record = [[Record alloc] initWithTableName:tableName];
        record.mode = UPDATE;
        
        int cols = sqlite3_column_count(statement);
        for(int i=0; i<cols; i++){
            
            NSString *colName = [NSString stringWithCString:sqlite3_column_name(statement, i) encoding:NSUTF8StringEncoding];
            if ([keyNames containsObject:colName]){
                [record addKeyField:colName value:getColumnString(statement, i)];
                
            }else{
                [record addField:colName value:getColumnString(statement, i)];
                
            }
        }
        [list addObject:record];
    }
    
    sqlite3_finalize(statement);
    
    return list;
}

int executeDbUpdate(const char* sql)
{
    char *errorMsg;
    if (sqlite3_exec(dBbase.database, sql, NULL, NULL, &errorMsg)!=SQLITE_OK) {
        NSLog(@"update data fail: %s",sql);
        NSLog(@"update data fail errorMsg: %s",errorMsg);
        sqlite3_free(errorMsg);
        //[estimationViewController showError:@"update data fail"];
        return -1;
    }
    return  1;
}


@end
